package com.doge.walknovel.business

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ValueAnimator
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.util.AttributeSet
import android.view.View
import android.view.animation.DecelerateInterpolator
import android.webkit.*
import android.widget.ProgressBar
import android.widget.TextView
import com.doge.wnpro.R
import com.doge.walknovel.core.BaseActivity
import com.doge.walknovel.core.account.AccountHelper
import com.doge.wnpro.databinding.ActivityWebBinding
import com.doge.walknovel.utils.*

class WebActivity : BaseActivity() {
    private val binding by lazy { ActivityWebBinding.inflate(layoutInflater) }
    private val url by lazy { intent.getStringExtra("url")!! }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        initialViews()
        binding.webView.loadUrl(url)
        log("WebActivity loadUrl [$url]")
        binding.loadingProgress.start()
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        binding.webView.reload()
    }

    private fun initialViews() {
        binding.toolbar.binding.pageBack.setOnClickCallback {
            if (canGoBack()) {
                binding.webView.goBack()
            } else {
                finish()
            }
        }

        val webSettings = binding.webView.settings
        webSettings.textZoom = 100
        webSettings.layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN
        webSettings.javaScriptEnabled = true
        webSettings.allowContentAccess = true
        webSettings.setAppCacheEnabled(false)
        webSettings.builtInZoomControls = false
        webSettings.useWideViewPort = true
        webSettings.loadWithOverviewMode = true
        webSettings.layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN
        webSettings.cacheMode = WebSettings.LOAD_NO_CACHE //设置缓存 // 解决js好像调用不了的问题 具体问 陈恩典
        webSettings.mixedContentMode =
            WebSettings.MIXED_CONTENT_ALWAYS_ALLOW // https://blog.csdn.net/zlgzh/article/details/70171746 https页面加载http图片
        webSettings.domStorageEnabled = true
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            webSettings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
        }
        webSettings.blockNetworkImage = false
        webSettings.javaScriptCanOpenWindowsAutomatically = true//支持js调用window.open方法
        webSettings.setSupportMultipleWindows(true)// 设置允许开启多窗口
        binding.webView.addJavascriptInterface(AndroidJs(), "android")//AndroidJS类对象映射到js的android对象
        binding.webView.setLayerType(View.LAYER_TYPE_HARDWARE, null)
        binding.webView.webViewClient = object : WebViewClient() {
            override fun onPageFinished(view: WebView?, url: String?) {
                super.onPageFinished(view, url)
                binding.toolbar.findViewById<TextView>(R.id.pageTitle).text = view?.title
            }

            override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
                if (url.startsWith("http:") || url.startsWith("https:")) {
                    view.loadUrl(url)
                } else {
                    val sendIntent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
                    startActivity(sendIntent)
                }
                return true
            }
        }
        binding.webView.webChromeClient = object : WebChromeClient() {
            override fun onProgressChanged(view: WebView, newProgress: Int) {
                if (newProgress >= 100) {
                    binding.loadingProgress.stop()
                }
            }
        }
    }

    private fun canGoBack(): Boolean {
        var canGoBack = false
        try {
            canGoBack = binding.webView.canGoBack()
        } catch (e: Throwable) {
            e.printStackTrace()
            return canGoBack
        }

        val url = binding.webView.url
        if (TextUtils.isEmpty(url) || "about:blank" == url) {
            return false
        }
        val uri = Uri.parse(url)
        val m = uri.getQueryParameter("m")
        if ("family".equals(m, ignoreCase = true)) {
            val a = uri.getQueryParameter("a")
            if ("home".equals(a!!, ignoreCase = true)) {
                canGoBack = false
            }
        }
        return canGoBack
    }

    override fun onBackPressed() {
        if (canGoBack()) {
            binding.webView.goBack()
        } else {
            finish()
        }
    }

    class AndroidJs : Any() {
        @JavascriptInterface
        fun userToken(): String = AccountHelper.token

        @JavascriptInterface
        fun language(): String = language.language

        @JavascriptInterface
        fun deviceType(): String = deviceType.toString()

        @JavascriptInterface
        fun requiredLogin() = runOnUI { AccountHelper.requiredLogin() }
    }

    companion object {
        private const val EXTRA_URL = "url"

        fun start(context: Context?, url: String?) {
            if (context == null || url == null) return
            context.startActivity(Intent(context, WebActivity::class.java).apply {
                if (context == appContext) flags = Intent.FLAG_ACTIVITY_NEW_TASK
                putExtra(EXTRA_URL, url)
            })
        }
    }
}


class HorizontalProgressView @JvmOverloads constructor(
    context: Context,
    attr: AttributeSet? = null,
    defStyleStyle: Int = 0
) : ProgressBar(context, attr, defStyleStyle) {

    private var dirtyAnim: ValueAnimator? = null
    private var isStarted = false

    fun stop() {
        isStarted = false
        dirtyAnim?.cancel()
        internalProcess(progress, 100, 100) {
            visibility = View.GONE
        }
    }

    fun start() {
        if (!isStarted) {
            isStarted = true
            visibility = View.VISIBLE

            internalProcess(0, 30, 200) {
                internalProcess(30, 70, 1000) {
                    internalProcess(70, 90, 5000) {
                        internalProcess(90, 95, Long.MAX_VALUE) {

                        }
                    }
                }
            }
        }
    }

    private fun internalProcess(
        start: Int,
        end: Int,
        d: Long,
        callback: () -> Unit
    ) {
        dirtyAnim?.cancel()
        dirtyAnim = ValueAnimator.ofInt(start, end)
            .apply {
                duration = d
                addListener(object : AnimatorListenerAdapter() {
                    var isCanceled = false

                    override fun onAnimationEnd(animation: Animator?) {
                        if (isCanceled) return
                        progress = end
                        callback()
                    }

                    override fun onAnimationCancel(animation: Animator?) {
                        isCanceled = true
                    }
                })
                addUpdateListener {
                    progress = it.animatedValue as Int
                }
                interpolator = DecelerateInterpolator()
                start()
            }

    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        dirtyAnim?.cancel()
    }
}